package com.kit.personalkit.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.kit.personalkit.common.JsonResponseBody;
import com.kit.personalkit.common.PageUtils;
import com.kit.personalkit.common.ResponseStatus;
import com.kit.personalkit.mapper.NoteMapper;
import com.kit.personalkit.pojo.dto.NoteDTO;
import com.kit.personalkit.pojo.dto.NotePageDTO;
import com.kit.personalkit.pojo.entity.Note;
import com.kit.personalkit.pojo.vo.NoteStandardVO;
import com.kit.personalkit.pojo.vo.NoteVO;
import com.kit.personalkit.security.CustomUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 处理笔记相关请求的控制器类
 *
 * @author hc
 */
@Slf4j
@RestController
@RequestMapping("/note/")
@Validated
public class NoteController {

    /**
     * 获得SpringBoot当前项目的路径：System.getProperty("user.dir")
     */
    private static String basePath = System.getProperty("user.dir");
    private static String notePath = basePath + "/notes/";
    private static String imgPath = basePath + "/images/";
    private static File realPath = new File(imgPath);
    private static File dir = new File(notePath);

    static{
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
    }

    static{
        if (!dir.exists()){
            dir.mkdirs();
        }
    }
    @Autowired
    private NoteMapper noteMapper;

    public NoteController() {
        log.info("创建控制器对象：NoteController");
    }

    /**
     * 跳转到编辑页面
     *
     * @return
     */
    @GetMapping("toEditor")
    public JsonResponseBody toEditor() {
        log.debug("开始处理【进入编辑页面】的请求");
        return JsonResponseBody.ok();
    }

    /**
     * 添加笔记
     * @return
     */
    @PostMapping("addNote")
    public JsonResponseBody addNote(@Validated NoteDTO noteDTO,
                                    @AuthenticationPrincipal CustomUserDetails cud) {
        log.debug("开始处理【新增笔记】的请求，参数：{}", noteDTO);
        Note note = new Note();
        BeanUtils.copyProperties(noteDTO,note);
        note.setUserId(cud.getUserId().longValue());
        note.setCreateTime(new Date());
        note.setUpdateTime(new Date());
        noteMapper.addNote(note);
        // 生成 Markdown 文件
        String title = note.getNoteTitle();
        String content = note.getNoteContent();

        String filename = title + ".md";
        String userFolderPath = notePath + cud.getUserId() + "/";
        File userFolder = new File(userFolderPath);
        if(!userFolder.exists()){
            userFolder.mkdirs();
        }

        File file = new File(userFolder,filename);
        try {
            FileWriter writer = new  FileWriter(file);
            writer.write(content);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JsonResponseBody.ok();
    }

    /**
     * 删除笔记
     *
     * @param id
     * @return
     */
    @GetMapping("deleteNote/{id:[0-9]+}")
    public JsonResponseBody deleteNote(@PathVariable("id") Long id ) {
        log.debug("开始处理【删除笔记】的请求，参数：{}", id);
        NoteStandardVO currentNote = noteMapper.getStandardById(id);
        if(currentNote == null){
            String message = "删除笔记失败，尝试删除的笔记数据不存在！";
            log.warn(message);
            return new JsonResponseBody(ResponseStatus.ERROR_NOT_FOUND,message);
        }
        int row = noteMapper.deleteNoteById(id);
        if(row != 1){
            String message = "删除笔记失败,请稍后重试！";
            return new JsonResponseBody(ResponseStatus.DELETE_FAIL,message);
        }
        return new JsonResponseBody(ResponseStatus.DELETE_SUCCESS);
    }

    /**
     * 修改笔记
     *
     * @return
     */
    @PostMapping("updateNote")
    public JsonResponseBody updateNote(@Validated NoteDTO noteDTO) {
        log.debug("开始处理【修改笔记】的请求，参数：{}", noteDTO);
        Long id = noteDTO.getNoteId();
        NoteStandardVO currentNote = noteMapper.getStandardById(id);
        if(currentNote == null){
            String message = "修改笔记失败，尝试修改的笔记数据不存在！";
            log.warn(message);
            return new JsonResponseBody(ResponseStatus.ERROR_NOT_FOUND,message);
        }
        Note note = new Note();
        BeanUtils.copyProperties(noteDTO,note);
        note.setUpdateTime(new Date());
        int row = noteMapper.updateNote(note);
        if(row != 1){
            String message = "修改笔记失败,请稍后重试！";
            return new JsonResponseBody(ResponseStatus.UPDATE_FAIL,message);
        }
        return new JsonResponseBody(ResponseStatus.UPDATE_SUCCESS);
    }

    /**
     * 获取笔记进行显示
     * @param id
     * @return
     */
    @GetMapping("showNote/{id:[0-9]+}")
    public JsonResponseBody show(@PathVariable("id") Long id){
        log.debug("开始处理【根据ID查询笔记】的请求，参数：{}", id);
        NoteStandardVO currentNote = noteMapper.getStandardById(id);
        if(currentNote == null){
            String message = "查询笔记失败，尝试查询的笔记数据不存在！";
            log.warn(message);
            return new JsonResponseBody(ResponseStatus.ERROR_NOT_FOUND,message);
        }
        NoteVO noteVO = noteMapper.getNoteById(id);
        return JsonResponseBody.ok(noteVO);
    }

    /**
     * 笔记列表
     *
     * @return
     */

    @PostMapping("noteList")
    public JsonResponseBody getNoteList(@RequestBody NotePageDTO notePageDTO,
                                        @AuthenticationPrincipal CustomUserDetails cud) {
        log.debug("开始处理[查询笔记列表]请求");
        if (cud == null){
            return new JsonResponseBody(ResponseStatus.NOT_LOGIN);
        }
        HashMap param = JSONUtil.parse(notePageDTO).toBean(HashMap.class);
        int pageIndex = notePageDTO.getPageIndex();
        int length = notePageDTO.getPageSize();
        int start = (pageIndex - 1) * length;
        Integer userId = cud.getUserId();
        param.put("start",start);
        param.put("length",length);
        param.put("userId",userId);
        ArrayList<HashMap> list = noteMapper.getNoteList(param);
        Long count = noteMapper.selectNoteCount(param);
        PageUtils pageUtils = new PageUtils(list,count,start,length);
        return JsonResponseBody.ok(pageUtils);
    }



    /**
     * 处理图片上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("file/upload")
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,@AuthenticationPrincipal CustomUserDetails cud) throws IOException {
        log.debug("开始处理[上传图片]的请求");
        //上传文件地址
        System.out.println("上传文件保存地址：" + realPath);

        String filename = file.getOriginalFilename();
        String userFolderPath = imgPath + cud.getUserId() + "/";
        File userFolder = new File(userFolderPath);
        if (!userFolder.exists()) {
            userFolder.mkdirs();
        }

        File newFile = new File(userFolder, filename);
        file.transferTo(newFile);

        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url", "/api/images/"+ cud.getUserId() + "/"+ filename);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }

}

